package production.practice.utils;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;
import production.practice.pojo.entity.SysUser;
import production.practice.pojo.entity.User;
import production.practice.pojo.fuction.authorization.TokenProperties;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用来获取当前用户登录信息
 */

@Component
@Data
public class SysUtil implements BeanFactoryAware {

    private static TokenProperties tokenProperties;

    @Resource
    private static RedisUtil redisUtil;

    private static ThreadLocal<User> threadLocal = new ThreadLocal<>();


    public static void setCurrentUser(User user) {
        threadLocal.set(user);
    }
    public static User getCurrentUserInfo() {
        return threadLocal.get();
    }

    public static boolean checkToken(String token) {
        if (BinaryUtils.isEmpty(token))
            return false;
        if (!token.startsWith("Bear "))
            return false;
        if (!token.contains(tokenProperties.getSalt()))
            return false;
        return true;
    }


    @PreDestroy
    public void destroy() {
        threadLocal.remove();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        TokenProperties bean = beanFactory.getBean(TokenProperties.class);
        redisUtil = beanFactory.getBean(RedisUtil.class);
        tokenProperties = bean;
    }

    public static String generateToken(User user) {
        final String prefix="Bear ";
        UUID uuid = UUID.randomUUID();
        //将未加密的信息存入redis
        redisUtil.set(uuid.toString(),user,tokenProperties.getExpire());
        String token = prefix + uuid.toString()+tokenProperties.getSalt();
        return token;
    }

    public static String deCodeToken(String token) {
       return token.substring(5).substring(0,token.length()-tokenProperties.getSalt().length());
    }



}
